package com.huiminpay.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.convert.AppConvert;
import com.huiminpay.merchant.dto.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.common.cache.execption.BizException;
import com.huiminpay.merchant.mapper.AppMapper;
import com.huiminpay.merchant.service.IAppService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class AppServiceImpl implements IAppService {
    @Autowired
    AppMapper appMapper;

    @Override
    public AppDTO createApp(AppDTO appDTO) {
        //校验名称的唯一
        QueryWrapper<App> queryWrapper= new QueryWrapper<>();
        queryWrapper.lambda().eq(App::getAppName,appDTO.getAppName());
       // LambdaQueryWrapper<App> queryWrapper =new  LambdaQueryWrapper<>();
       // queryWrapper.eq(App::getAppName,appDTO.getAppName());
        Integer integer = appMapper.selectCount(queryWrapper);
        if (integer>0){
            throw new BizException(CommonErrorCode.E_200238);
        }
        //对象转换
        App app = AppConvert.INSTANCE.dto2entity(appDTO);

        //设置appId为uuID
        app.setAppId(RandomUuidUtil.getUUID());
        //保存，
        appMapper.insert(app);
        return AppConvert.INSTANCE.entity2dto(app);
    }

    @Override
    public List<AppDTO> myApps(Long merchantId) {
        //校验查询
        QueryWrapper<App> queryWrapper= new QueryWrapper<>();
       // LambdaQueryWrapper<App> queryWrapper =new  LambdaQueryWrapper<>();
        queryWrapper.lambda().eq(App::getMerchantId,merchantId);
        List<App> apps = appMapper.selectList(queryWrapper);

        return AppConvert.INSTANCE.entity2dtos(apps);
    }

    @Override
    public AppDTO updateApp(AppDTO appDTO) {
        //校验名称的唯一
        QueryWrapper<App> queryWrapper= new QueryWrapper<>();
      //  LambdaQueryWrapper<App> queryWrapper =new  LambdaQueryWrapper<>();
        queryWrapper.lambda().eq(App::getAppName,appDTO.getAppName());
        Integer integer = appMapper.selectCount(queryWrapper);
        if (integer>0){
            throw new BizException(CommonErrorCode.E_200238);
        }
        //更新根据Appid
        App app = AppConvert.INSTANCE.dto2entity(appDTO);
        UpdateWrapper<App> ww= new UpdateWrapper<>();
      //  LambdaUpdateWrapper<App> ww = new LambdaUpdateWrapper<>();
        ww.lambda().eq(App::getAppId,appDTO.getAppId());
        int update = appMapper.update(app, ww);
        return appDTO;
    }
}
